package cn.lee.cplibrary.util.permissionutil;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.view.Gravity;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.lee.cplibrary.util.LogUtil;
import cn.lee.cplibrary.util.ToastUtil;
import cn.lee.cplibrary.util.dialog.CpComDialog;
import cn.lee.cplibrary.util.system.AppUtils;
import cn.lee.cplibrary.util.timer.TimeUtils;

/**
 * create by ChrisLee on 2021/10/18
 */
public class CPPermissionUtil {
    protected Activity activity;
    protected Fragment fragment;
    protected PermissionUtil permissionUtil;
    protected String guideDialogMsg ="当前功能缺少必要权限。\n请点击\"设置\"-\"权限\"-打开所需权限";//引导对话框上显示的文字
    protected boolean isShowGuideDialog = true;//用户永久拒绝需要的权限时，是否显示引导对话框，使用时候可自行设置
    protected boolean isHandleResult = true;//是否处理申请结果
    protected GrantedCallBack callBack;
    /**
     * 在Activity中使用
     */
    public CPPermissionUtil(Activity activity) {
        this.activity = activity;
        permissionUtil = new PermissionUtil(proxy);
    }

    /**
     * 在Fragment中使用
     */
    public CPPermissionUtil(Fragment fragment) {
        this.fragment = fragment;
        this.activity = fragment.getActivity();
        permissionUtil = new PermissionUtil(proxy);

    }

    /**
     * 申请权限
     * 注意顺序：先setCallBack 再 requestPermissions
     */
    public void requestPermissions(String[] pers, int requestCode) {
        if (fragment == null) {
            permissionUtil.requestPermissions(activity, requestCode, pers);
        } else {
            permissionUtil.requestPermissions(fragment, requestCode, pers);
        }
    }

    /**
     * （必须调用本方法）
     * 权限申请结果处理,在Activity或者Fragment的onRequestPermissionsResult方法中的super方法上一行调用
     * eg：
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (isHandleResult) {
            if (fragment == null) {
                permissionUtil.onRequestPermissionsResult(activity, requestCode, permissions, grantResults);
            } else {
                permissionUtil.onRequestPermissionsResult(fragment, requestCode, permissions, grantResults);
            }
        }

    }

    public PermissionProxy proxy = new PermissionProxy() {
        @Override
        public void granted(Object source, int requestCode) {
            if (callBack != null) {
                callBack.granted(source, requestCode);
            }
        }

        @Override
        public void denied(Object source, int requestCode, List deniedPermissions) {
            LogUtil.i("", "denied=" + deniedPermissions);
            Map<String, List<String>> map = PerUtils.groupDeniedPermissions(activity, deniedPermissions);
            List<String> list = map.get("show");
            if (list.size() > 0) {//尚有未允许的权限，且允许弹框的，后面不执行deniedNoShow，
                if (callBack != null) {
                    callBack.needCheck();
                }
            }
        }

        @Override
        public void deniedNoShow(Object source, int requestCode, List noShowPermissions) {
            LogUtil.i("", "deniedNoShow=" + noShowPermissions);
            showGuideDialog(activity);
        }

        @Override
        public void rationale(Object source, int requestCode) {

        }

        @Override
        public boolean needShowRationale(int requestCode) {
            return false;
        }
    };

    protected void showGuideDialog(final Activity c) {
         if (!isShowGuideDialog) {
            ToastUtil.showToast(c, "当前功能缺少必要权限");
            return;
        }
        TimeUtils.isCheckFastClick = false;
        CpComDialog.Builder.builder(c).
                setTitle("提示").setContent(guideDialogMsg).setTxtCancel("拒绝").setSure("开启")
                .setTitleSize(20).setContentSize(16).setBtnSize(20)
                .setBtnCancelColor(Color.parseColor("#8d8d8d"))
                .setGravity(Gravity.LEFT)
                .setCancel(false)
                .build().show2BtnDialog(new CpComDialog.Dialog2BtnCallBack() {
            @Override
            public void sure() {
                if (callBack != null) {
                    callBack.needCheck();
                }
                AppUtils.jumpAppSettingInfo(c);
            }

            @Override
            public void cancel() {
                if (callBack != null) {
                    callBack.denied();
                }
            }
        });
        TimeUtils.isCheckFastClick = true;
    }

    public CPPermissionUtil setShowGuideDialog(boolean showGuideDialog) {
        isShowGuideDialog = showGuideDialog;
        return this;
    }

    public CPPermissionUtil setHandleResult(boolean handleResult) {
        isHandleResult = handleResult;
        return this;
    }

    public CPPermissionUtil setGuideDialogMsg(String guideDialogMsg) {
        this.guideDialogMsg = guideDialogMsg;
        return this;
    }

    public CPPermissionUtil setCallBack(GrantedCallBack callBack) {
        this.callBack = callBack;
        return this;
    }

    public interface GrantedCallBack {
        void granted(Object source, int requestCode);//全部允许
        /**
         * 点击引导弹框的拒绝按钮
         */
        void denied();
        /**
         * 需要继续检测权限情况：点击引导弹框的设置按钮、或点击权限不允许按钮
         */
        void needCheck();
    }

}